package view;

import javax.swing.*;
import java.awt.*;
import model.User;
import dao.UserDAO;

public class LoginDialog extends JDialog {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private User loggedInUser;
    
    public LoginDialog(JFrame parent) {
        super(parent, "用户登录", true);
        
        setLayout(new GridLayout(3, 2, 5, 5));
        
        // 用户名输入
        add(new JLabel("用户名："));
        usernameField = new JTextField();
        add(usernameField);
        
        // 密码输入
        add(new JLabel("密码："));
        passwordField = new JPasswordField();
        add(passwordField);
        
        // 按钮
        JButton loginBtn = new JButton("登录");
        JButton cancelBtn = new JButton("取消");
        
        loginBtn.addActionListener(e -> login());
        cancelBtn.addActionListener(e -> System.exit(0));
        
        add(loginBtn);
        add(cancelBtn);
        
        pack();
        setLocationRelativeTo(parent);
        setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    }
    
    private void login() {
        String username = usernameField.getText();
        String password = new String(passwordField.getPassword());
        
        UserDAO dao = new UserDAO();
        loggedInUser = dao.login(username, password);
        
        if (loggedInUser != null) {
            dispose();
        } else {
            JOptionPane.showMessageDialog(this, "用户名或密码错误！", "登录失败", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    public User getLoggedInUser() {
        return loggedInUser;
    }
} 